package com.zhan.rkforum.controller;

import com.google.code.kaptcha.Producer;
import com.zhan.rkforum.bean.User;
import com.zhan.rkforum.service.UserService;
import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.CommunityUtil;
import com.zhan.rkforum.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wujiazhan
 * @className LoginController
 * @description TODO
 * @date 2021-05-27 17:07
 */

@Controller
@Slf4j
public class LoginController implements CommunityConstant {

    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private Producer kaptcha;


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    /**
     * 跳转登陆页面
     * @return 跳转到注册页面
     */
    @GetMapping(value = "/register")
    public String toRegister(){
        return "site/register";
    }

    /**
     * 注册控制器
     * @return 注册结果
     */
    @PostMapping(value = "/register")
    public String register(Model model,User user){
        Map<String, Object> map = userService.register(user);
        if (ObjectUtils.isEmpty(map) || map.isEmpty()) {
            model.addAttribute("msg", "注册成功,我们已经向您的邮箱发送了一封激活邮件,请尽快激活!");
            model.addAttribute("target", "/index");
            return "site/operate-result";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "site/register";
        }
    }

    @GetMapping("/activation/{username}/{code}")
    public String active(Model model, @PathVariable("username") String username, @PathVariable("code") String code){
        int result = userService.active(username, code);
        if (result == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功,您的账号已经可以正常使用了!");
            model.addAttribute("target", "/login");
        } else if (result == ACTIVATION_REPEAT) {
            model.addAttribute("msg", "无效操作,该账号已经激活过了!");
            model.addAttribute("target", "/index");
        } else {
            model.addAttribute("msg", "激活失败,您提供的激活码不正确!");
            model.addAttribute("target", "/index");
        }
        return "site/operate-result";
    }

    @GetMapping(value = "/kaptcha")
    public void getKaptcha(HttpServletResponse response/*, HttpSession session*/){
        String text = kaptcha.createText();
        String owner = CommunityUtil.generateUuid();
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(owner);
        Cookie check_code_cookie = new Cookie("kaptchaKey", kaptchaKey);
        check_code_cookie.setPath(contextPath);
        check_code_cookie.setMaxAge(60);//设置过期时间为60s
        response.addCookie(check_code_cookie);
        redisTemplate.opsForValue().set(kaptchaKey,text,60, TimeUnit.SECONDS);//验证码存入Redis
        //session.setAttribute("sessionCheckCode", text);
        BufferedImage image = kaptcha.createImage(text);
        //响应数据的格式
        response.setContentType("image/png");
        try {
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping(value = "/login")
    public String toLogin(){
        return "site/login";
    }

    @PostMapping(value = "/login/form")
    public String login(String username, String password, String code, boolean rememberMe,
                        /*HttpSession session, */Model model, HttpServletResponse response, @CookieValue(value = "kaptchaKey")String  kaptchaKey) {

        //String checkCode = (String) session.getAttribute("sessionCheckCode");
        String checkCode = null;
        if(StringUtils.isNotBlank(kaptchaKey)){
            checkCode = (String) redisTemplate.opsForValue().get(kaptchaKey);
            logger.info("在Redis数据库中获取验证码" + checkCode);
        }

        if(StringUtils.isBlank(checkCode) || StringUtils.isBlank(code) || !checkCode.equals(code)){
            model.addAttribute("codeMsg","验证码不正确");
            return "site/login";
        }

        int expiredSeconds = rememberMe ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        String ticket = "ticket";
        if(map.containsKey(ticket)){
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setMaxAge(expiredSeconds);
            cookie.setPath(contextPath);
            response.addCookie(cookie);
            return "redirect:/index";
        } else{
            //不要转化成字符串，因为获取到的可能是空值，转化会产生空指针异常
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            return "site/login";
        }
    }


    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket){
        userService.logout(ticket);
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }

}
